import React, { useState, useEffect, useCallback } from 'react';
import { Button, Modal, Table, Form, Input } from 'antd';
import { ColumnsType } from 'antd/lib/table';
import { flatTryCatch } from '../../../../servers/http';
import { getTemplateList } from 'admin/servers/servers';
import { debounce } from 'lodash';

interface Props {
  onTemplateFromChild: (data: string[]) => void;
}

const SelectTemplate: React.FC<Props> = ({ onTemplateFromChild }) => {
  /** 弹窗显隐 */
  const [isModalVisible, setIsModalVisible] = useState(false);

  const handleTriggerModal = (flag: boolean) => {
    setIsModalVisible(flag);
  };

  const handleOk = () => {
    onTemplateFromChild(pitchTemplate);
    handleTriggerModal(false);
  };

  /** 数据列表 */
  const [form] = Form.useForm();
  const [tableDataList, setTableDataList] = useState([]);
  const [tableLoading, setTableLoading] = useState<boolean>(false);
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0,
    showTotal: (total: number) => `共${total}条`,
  });
  const columns: ColumnsType = [
    { title: '模板名称', dataIndex: 'name' },
    { title: '模板内容', dataIndex: 'content' },
  ];

  // 获取数据
  const fetchDataList = useCallback(async (values: any, page: number, limit: number) => {
    setTableLoading(true);
    const params = { page, limit, ...values };
    const { response, error } = await flatTryCatch(getTemplateList(params));
    setTableLoading(false);
    if (error) return;

    const { totalCount = 0, list = [], currPage = 1, pageSize = 10 } = response.data ?? {};
    setTableDataList(list);
    setPagination({
      current: currPage,
      pageSize,
      total: totalCount,
      showTotal: (total: number) => `共${total}条`,
    });
  }, []);

  /**操作: 搜索 */
  const handleFinish = debounce((values: any) => {
    fetchDataList(values, pagination.current, pagination.pageSize);
  }, 500);

  /**操作: 重置 */
  const handleReset = debounce(() => {
    form.resetFields();
    fetchDataList({}, 1, pagination.pageSize);
  }, 500);

  /**操作: 页码改变 */
  const handleTableChange = newPagination => {
    setPagination(newPagination);
    fetchDataList({}, newPagination.current, newPagination.pageSize);
  };

  useEffect(() => {
    fetchDataList({}, 1, 10);
  }, [fetchDataList]);

  /** 选择数据 */
  const [pitchTemplate, setPitchTemplate] = useState(null);
  const rowSelection = {
    onChange: (selectedRowKeys: React.Key[], selectedRows) => {
      setPitchTemplate(selectedRows[0]);
    },
  };

  return (
    <div>
      <Button type="primary" onClick={() => handleTriggerModal(true)}>
        手动选择模板
      </Button>
      <Modal
        title="选择模板"
        width={740}
        visible={isModalVisible}
        onOk={handleOk}
        onCancel={() => handleTriggerModal(false)}
      >
        <Form layout="inline" form={form} onFinish={handleFinish} style={{ marginBottom: '20px' }}>
          <Form.Item label="模板名称" name="name">
            <Input placeholder="请输入模板名称" />
          </Form.Item>
          <Form.Item>
            <Button type="primary" htmlType="submit">
              搜索
            </Button>
            <Button style={{ marginLeft: 8 }} onClick={handleReset}>
              重置
            </Button>
          </Form.Item>
        </Form>
        <Table
          rowSelection={{
            type: 'radio',
            ...rowSelection,
          }}
          loading={tableLoading}
          dataSource={tableDataList}
          columns={columns}
          rowKey="id"
          pagination={pagination}
          onChange={handleTableChange}
        />
      </Modal>
    </div>
  );
};

export default SelectTemplate;
